<template>
  <div class="base-container" id="main">
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <!-- 基本信息 -->
    <t-form ref="form" :key="activeForm" class="step-form" :data="formData" @submit="onSubmit($event, 1)"
      labelWidth="180px" :rules="rules">
      <t-card class="step-card" size="small" title="基本信息">
        <t-row style="align-items: stretch" :gutter="14">

          <t-col :span="6">

            <t-form-item label="项目名称：" name="projectName">
              <t-tooltip theme="light">
                <template v-if="oldPorjectList.length > 0" #content>
                  <t-divider style="margin: 0"> 相似项目列表</t-divider>
                  <t-link v-for="(item, index) in oldPorjectList" :key="index"
                    @click="dialog.objId = item.projectId; dialog.header = item.projectName; dialog.open_project_detail = true"
                    hover="color" theme="primary">{{ item.projectName }}
                  </t-link>
                </template>
                <t-input @change="onProjectNameChange" clearable style="width: 390px"
                  v-model="formData.projectName"></t-input>
              </t-tooltip>
            </t-form-item>
            <t-form-item label="承担单位：" name="declareDeptName">
              <t-input clearable style="width: 390px" disabled v-model="formData.declareDeptName"></t-input>
            </t-form-item>
            <t-form-item label="组织方式：" name="orgMode">
              <t-select clearable style="width: 390px" v-model="formData.orgMode" :options="dict.type.org_mode">
              </t-select>
            </t-form-item>
            <t-form-item label="所属产业：" name="owningIndustry">
              <t-select clearable style="width: 390px" v-model="formData.owningIndustry"
                :options="dict.type.owning_industry">
              </t-select>
            </t-form-item>
            <t-form-item label="依托平台：" name="supportPlatform">
              <t-select clearable style="width: 390px" v-model="formData.supportPlatform"
                :options="dict.type.support_platform">
              </t-select>
            </t-form-item>
            <t-form-item label="项目开始时间：" name="startDate">
              <t-date-picker clearable style="width: 390px" v-model="formData.startDate"></t-date-picker>
            </t-form-item>
            <t-form-item label="预计总投入：" name="adviceFunding">
              <t-input-adornment append="万元">
                <t-input-number :decimal-places="2"
                  @keyup="() => { if (formData.adviceFunding) { formData.adviceFunding = Number((formData.adviceFunding || 0).toString().match(/^\d+(?:\.\d{0,2})?/)) } }"
                  :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                  v-model="formData.adviceFunding" theme="normal" :min="0"></t-input-number>
              </t-input-adornment>
            </t-form-item>
          </t-col>

          <t-col :span="6">
            <t-form-item label="项目编号：" name="projectNum">
              <t-input clearable style="width: 390px" v-model="formData.projectNum"></t-input>
            </t-form-item>
            <t-form-item label="项目类型：" name="projectType">
              <t-select @input-change="(val) => { formData.projectType = val }" filterable clearable
                style="width: 390px" v-model="formData.projectType" :options="dict.type.three_project_type">
              </t-select>
            </t-form-item>
            <t-form-item label="项目领域：" name="projectDomain">
              <t-select clearable style="width: 390px" v-model="formData.projectDomain"
                :options="dict.type.three_project_domain">
              </t-select>
            </t-form-item>
            <t-form-item label="所属学科：" name="owningSubject">
              <t-select clearable style="width: 390px" v-model="formData.owningSubject"
                :options="dict.type.owning_subject">
              </t-select>
            </t-form-item>
            <t-form-item label="所属创新团队：" name="owningTeam">
              <t-select clearable style="width: 390px" v-model="formData.owningTeam" :options="dict.type.owning_team">
              </t-select>
            </t-form-item>
            <t-form-item label="项目结束时间：" name="endDate">
              <t-date-picker clearable style="width: 390px" v-model="formData.endDate"></t-date-picker>
            </t-form-item>
            <t-form-item label="财政科技经费：" name="subsidyFunding">
              <t-input-adornment append="万元">
                <t-input-number :decimal-places="2"
                  @keyup="() => { if (formData.subsidyFunding) { formData.subsidyFunding = Number((formData.subsidyFunding || 0).toString().match(/^\d+(?:\.\d{0,2})?/)) } }"
                  :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                  v-model="formData.subsidyFunding" theme="normal" :min="0"></t-input-number>
              </t-input-adornment>
            </t-form-item>

          </t-col>

        </t-row>
        <t-row>
          <!-- <t-col :span="12" class="title"><span class="require">*</span>项目内容摘要</t-col> -->
        </t-row>
        <t-row>
          <t-col :span="12">
            <t-form-item name="digest" label="项目内容摘要：">
              <!-- <template #label>
                <span class="textTips-color-red">如果遇到格式问题，请先将内容复制到word中调整好，再黏贴到系统中</span>
              </template> -->
              <tiny-mce-editor :key="activeForm" :textLength.sync="lengthLimitObj.digest"
                v-model="formData.digest"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <!-- <t-col :span="12" class="title"><span class="require">*</span>关键词：</t-col> -->
          <t-col :span="12">
            <t-form-item name="keyWord" label="关键词：">
              <t-select v-model="formData.keyWord" creatable filterable multiple placeholder="手输支持自定义创建"
                :options="dict.type.kjxm_key_word" @create="createKeyWordOptions" @change="onKeyWordChange">
              </t-select>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row></t-row>
      </t-card>

      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="12">
          <t-card class="step-card" size="small" title="项目主要负责人">
            <t-row>
              <t-col :span="6">
                <t-form-item label="姓名：" name="projectLeader.name">
                  <t-select v-model="formData.projectLeader.name" creatable filterable @change="onLeaderNameChange"
                    placeholder="请输入姓名" :loading="leaderLoading" @search="remoteProjectLeaderMethod"
                    :options="projectLeaderOptions" @create="createProjectLeaderOptions" style="width: 390px" />
                </t-form-item>
                <t-form-item label="身份证号：" name="projectLeader.idCard">
                  <t-input style="width: 390px" @change="onIdCardChange" placeholder="请输入身份证号" clearable
                    v-model="formData.projectLeader.idCard"></t-input>
                </t-form-item>
                <t-form-item label="性别：" name="projectLeader.sex">
                  <t-select style="width: 390px" placeholder="请选择性别" :options="dictTypes.sys_user_sex"
                    v-model="formData.projectLeader.sex">
                  </t-select>
                </t-form-item>
                <t-form-item label="出生年月：" name="projectLeader.birthDate">
                  <t-date-picker placeholder="请选择生日" mode="month" v-model="formData.projectLeader.birthDate"
                    :disable-date="{
                      after: dayjs().endOf('month').add(-18, 'year').format()
                    }" style="width: 390px"></t-date-picker>
                </t-form-item>

                <t-form-item label="工作单位：" name="projectLeader.companyId">
                  <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                    @change="(val, content) => { formData.projectLeader.company = content.node.data.label }"
                    v-model="formData.projectLeader.companyId" :data="deptMenuOptions"
                    placeholder="选择工作单位"></t-tree-select>
                </t-form-item>
                <t-form-item label="联系电话：" name="projectLeader.phone">
                  <t-input style="width: 390px" placeholder="请输入手机号码" clearable
                    v-model="formData.projectLeader.phone"></t-input>
                </t-form-item>
                <t-form-item label="通讯地址：" name="projectLeader.address">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.address"></t-input>
                </t-form-item>
                <t-form-item label="电子信箱：" name="projectLeader.email">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.email"></t-input>
                </t-form-item>
                <t-form-item label="邮编：" name="projectLeader.postCode">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.postCode"></t-input>
                </t-form-item>
                <!-- <t-form-item label="毕业院校：" name="projectLeader.school">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.school"></t-input>
                </t-form-item> -->
              </t-col>
              <t-col :span="6">
                <t-form-item label="学历：" name="projectLeader.education">
                  <t-select style="width: 390px" v-model="formData.projectLeader.education" clearable
                    placeholder="请选择学历" :options="dictTypes.education">
                  </t-select>
                </t-form-item>
                <t-form-item label="学位：" name="projectLeader.degree">
                  <t-select style="width: 390px" v-model="formData.projectLeader.degree" clearable placeholder="请选择学位"
                    :options="dictTypes.degree">
                  </t-select>
                </t-form-item>
                <t-form-item label="所学专业：" name="projectLeader.majorName">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.majorName"></t-input>
                </t-form-item>
                <t-form-item label="现从事专业：" name="projectLeader.majorNowName">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.majorNowName"></t-input>
                </t-form-item>
                <t-form-item label="职务：" name="projectLeader.duty">
                  <t-input style="width: 390px" clearable v-model="formData.projectLeader.duty"></t-input>
                </t-form-item>
                <t-form-item label="技术职称：" name="projectLeader.profTitId">
                  <t-tree-select clearable @change="onProfTitIdChange" filterable style="width: 390px"
                    :treeProps="{ keys: { value: 'id', label: 'name' }, valueMode: 'onlyLeaf' }"
                    v-model="formData.projectLeader.profTitId" :data="profTitOptions"
                    placeholder="技术职称"></t-tree-select>
                  <!--                    <t-input style="width: 390px" clearable v-model="formData.projectLeader.profTitId"-->
                  <!--                    ></t-input>-->
                </t-form-item>
                <t-form-item label="职称：" name="projectLeader.profTit">
                  <t-select disabled style="width: 390px" v-model="formData.projectLeader.profTit" clearable
                    placeholder="请选择职称" :options="dictTypes.prof_tit">
                  </t-select>
                </t-form-item>
                <!-- <t-form-item label="在本项目中承担的任务：" name="projectLeader.task">
                  <t-textarea style="width: 390px" clearable :autosize="{ minRows: 3 }"
                    v-model="formData.projectLeader.task" placeholder="请输入内容" />
                </t-form-item> -->
              </t-col>
            </t-row>
          </t-card>
        </t-col>
      </t-row>
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="12">
          <t-card class="step-card" size="small" title="附件信息">
            <t-row>
              <t-col :span="12">
                <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
                  <template #id="{ row, rowIndex }">
                    {{ rowIndex + 1 }}
                  </template>
                  <template #op="{ row }">
                    <file-upload v-model="row.fileIds" :moduleKey="row.moduleKey" :fileList="row.fileLists"
                      :multiple="true">
                      <t-button variant="outline">
                        <t-icon name="cloud-upload" slot="icon" />
                        点击上传
                      </t-button>
                    </file-upload>
                  </template>
                  <!-- <template #c1="{row}">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template> -->
                </t-table>
              </t-col>
            </t-row>
          </t-card>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="11" class="query-form-inline">
          <!-- <t-button variant="outline" @click="close">返回</t-button> -->
          <!-- <t-button theme="primary" @click="onSubmit($event, 1)" type="submit">{{ check() ? '暂存' : '确认修改' }}</t-button> -->
          <!-- <t-tooltip v-if="check()" :content="formData.isOldProject === '1' ? '提交后不会进入审批流程' : '提交后不可再编辑会进入审批流程'">
            <t-button :disabled="isCommit" theme="primary" @click="onSubmit($event, 2)" type="submit">
              {{ formData.isOldProject === '1' ? '提交' : '提交到单位管理员' }}
            </t-button>
          </t-tooltip> -->
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit">提交</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 附件信息 -->
    <project-detail-dialog :header="dialog.header" :hide-info="true" :objId="dialog.objId"
      :visible.sync="dialog.open_project_detail" v-if="dialog.open_project_detail"></project-detail-dialog>

  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import { getDictList } from "@/api/system/dict/data";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";

import ProjectDetailDialog from "./components/project-detail-dialog.vue";
import FileUpload from "@/components/FileUpload/index.vue"
import { getFiles } from "@/api/common";
import { getIdCardBirthday, getIdCardAge } from '@/utils/common';
import dayjs from "dayjs";

export default {
  name: "three_project_apply",
  dicts: ['kjxm_key_word', 'org_mode', 'owning_industry', 'support_platform', 'three_project_type', 'three_project_domain', 'owning_subject', 'owning_team'],
  components: {
    TinyMceEditor,
    ProjectDetailDialog,
    FileUpload
  },
  data () {
    return {
      file_domain: VITE_FILE_DOMAIN,
      site_tag: import.meta.env.VITE_SITE_TAG,
      dialog: {
        data: [],
        data2: [],
        openSearchMember: false,
        name: '',
        type: 1,
      },
      leaderLoading: false,
      projectLeaderOptions: [],
      applyLoading: false,
      lengthLimitObj: {
        digest: 0,
        digestMax: 500,
      },

      adviceFunding: 0,
      subsidyFunding: 0,

      oldUser: null,
      dayjs,

      projectCategoryColumns: [
        {
          colKey: "name",
          title: "类别名称",
        },
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64,
          checkProps: ({ row }) => ({ disabled: row.children && row.children.length > 0 }),
        },
        {
          colKey: "categoryType",
          title: "类型",
          align: "center",
          width: 100
        },
        {
          colKey: "startDate",
          title: "申报开始时间",
          align: "center",
          width: 200
        },
        {
          colKey: "endDate",
          title: "申报结束时间",
          align: "center",
          width: 200
        },
        {
          colKey: "declareEndDate",
          title: "申报单位审批截止时间",
          align: "center",
          width: 200
        },
        {
          colKey: "manageEndDate",
          title: "归口单位推荐截止时间",
          align: "center",
          width: 200
        },
        {
          colKey: "applyStatus",
          title: "申报状态",
          align: "center",
          width: 200
        },
        {
          colKey: 'note',
          title: "描述",
          ellipsis: true
        },
      ],
      projectCategoryColumns2: [
        // {
        //   colKey: "name",
        //   title: "类别名称",
        // },
        // {
        //   colKey: 'row-select',
        //   type: 'single',
        //   title: "选择",
        //   width: 64,
        //   checkProps: ({row}) => ({disabled: row.children && row.children.length > 0}),
        // },
        // {
        //   colKey: "categoryType",
        //   title: "类型",
        //   align: "center",
        //   width: 100
        // },
        {
          colKey: "startDate",
          title: "申报开始时间",
          align: "center",
          width: 200
        },
        {
          colKey: "endDate",
          title: "申报结束时间",
          align: "center",
          width: 200
        },
        {
          colKey: "declareEndDate",
          title: "申报单位审批截止时间",
          align: "center",
          width: 200
        },
        {
          colKey: "manageEndDate",
          title: "归口单位推荐截止时间",
          align: "center",
          width: 200
        },
        {
          colKey: "applyStatus",
          title: "申报状态",
          align: "center",
          width: 200
        },
        {
          colKey: 'note',
          title: "描述",
          ellipsis: true
        },
      ],
      projectFileData: [
        {
          id: 1,
          c1: "申报阶段文件",
          c2: "是",
          moduleKey: "03projectLXWJ",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 2,
          c1: "合同阶段文件",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "03projectHTWJ",
          require: true,
        },
        {
          id: 3,
          c1: "验收阶段文件",
          c2: "是",
          // c3: 'view/模板/项目组科研诚信承诺书.pdf',
          fileIds: [],
          fileLists: [],
          moduleKey: "03projectYSWJ",
          require: true,
        },
        {
          id: 6,
          c1: "其他",
          c2: "否",
          moduleKey: "03projectQT",
          fileIds: [],
          fileLists: [],
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],

      isCommit: false,
      profTitOptions: [],
      menuOptions: [],
      deptMenuOptions: [],
      taskId: null,
      activeForm: null,
      dictTypes: {},
      formData: {
        projectName: '',
        declareDeptName: '',
        orgMode: '',
        owningIndustry: '',
        supportPlatform: '',
        startDate: '',
        adviceFunding: null,
        keyWord: [],
        projectNum: '',
        projectType: '',
        projectDomain: '',
        owningSubject: '',
        owningTeam: '',
        endDate: '',
        subsidyFunding: null,
        digest: '',


        projectCategory: '',

        // projectStatus: 1, // 暂存传1，提交传2
        isOldProject: '0',
        projectLeader: {
          id: null,
          name: '',
          sex: '',
          birthDate: '',
          phone: '',
          address: '',
          email: '',
          postCode: '',
          profTit: '',
          school: '',
          majorName: '',
          degree: '',
          duty: '',
          // departmentId: null,
          companyId: null,
          company: '',
          profTitId: null,
          workDepartment: '',
          majorNowName: '',
          task: '',
          type: '1',
          isAssist: '0',
          idCard: '',
          education: '',
        },
      },
      rules: {
        keyWord: [{ required: true, validator: (val) => val && val.length, message: "关键词不能为空", type: "error" }],

        projectName: [
          {
            required: true,
            message: "项目名称不能为空",
          },
        ],
        declareDeptName: [
          {
            required: true,
            message: "承担单位不能为空",
          },
        ],
        orgMode: [
          {
            required: true,
            message: "组织方式不能为空",
          },
        ],
        owningIndustry: [
          {
            required: true,
            message: "所属产业不能为空",
          },
        ],
        supportPlatform: [
          {
            required: true,
            message: "依托平台不能为空",
          },
        ],
        projectDomain: [
          {
            required: true,
            message: "项目领域不能为空",
          },
        ],
        owningSubject: [
          {
            required: true,
            message: "所属学科不能为空",
          },
        ],
        owningTeam: [
          {
            required: true,
            message: "所属创新团队不能为空",
          },
        ],
        projectNum: [
          {
            required: true,
            message: "项目编号不能为空",
          },
        ],

        projectType: [
          {
            required: true,
            message: "项目类型不能为空",
          },
        ],
        adviceFunding: [
          {
            required: true,
            message: "预计总投入不能为空",
          },
        ],
        subsidyFunding: [
          {
            required: true,
            message: "财政科技经费不能为空",
          },
        ],
        digest: [
          {
            required: true,
            message: "项目内容摘要不能为空",
          }
        ],

        startDate: [
          {
            required: true,
            message: "项目开始时间不能为空",
          },
          // {
          //   validator: (val) => {
          //     if (val && this.formData.endDate) {
          //       const startTime = new Date(val).getTime()
          //       const endTime = new Date(this.formData.endDate).getTime()
          //       return startTime >= endTime;
          //     }
          //     return true;
          //   }, message: "项目开始时间一定大于项目结束日期", type: "error"
          // },
        ],
        endDate: [
          {
            required: true,
            message: "项目结束时间不能为空",
          },
          {
            validator: (val) => {
              if (val && this.formData.startDate) {
                const startTime = new Date(this.formData.startDate).getTime()
                const endTime = new Date(val).getTime()
                return startTime <= endTime;
              }
              return true;
            }, message: "项目开始时间不能大于结束时间", type: "error"
          },
        ],

        // 'projectLeader.workDepartment': [
        //   {
        //     required: true,
        //     message: "项目主要负责人工作单位不能为空",
        //   },
        // ],
        'projectLeader.companyId': [
          {
            required: true,
            message: "项目主要负责人工作单位不能为空",
          },
        ],
        'projectLeader.name': [
          {
            required: true,
            message: "项目主要负责人姓名不能为空",
          },
        ],
        'projectLeader.sex': [
          {
            required: true,
            message: "项目主要负责人性别不能为空",
          },
        ],
        'projectLeader.birthDate': [
          {
            required: true,
            message: "项目主要负责人生日不能为空",
          },
        ],
        'projectLeader.idCard': [
          {
            required: true,
            message: "项目主要负责人身份证号不能为空",
          },
          {
            message: "项目主要负责人身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        'projectLeader.phone': [
          {
            required: true,
            message: "项目主要负责人联系电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "项目主要负责人联系电话请输入正确的手机号码",
          },
        ],
        'projectLeader.address': [
          {
            required: true,
            message: "项目主要负责人地址不能为空",
          },
        ],
        'projectLeader.email': [
          {
            required: true,
            message: "项目主要负责人邮箱不能为空",
          },
          { email: { ignore_max_length: true }, message: '请输入正确的邮箱地址' }
        ],
        'projectLeader.postCode': [
          {
            required: true,
            message: "项目主要负责人邮编不能为空",
          },
        ],
        'projectLeader.school': [
          {
            required: true,
            message: "项目主要负责人毕业院校不能为空",
          },
        ],
        'projectLeader.education': [
          {
            required: true,
            message: "项目主要负责人学历不能为空",
          },
        ],
        'projectLeader.degree': [
          {
            required: true,
            message: "项目主要负责人学位不能为空",
          },
        ],
        'projectLeader.majorName': [
          {
            required: true,
            message: "项目主要负责人所学专业不能为空",
          },
        ],
        'projectLeader.majorNowName': [
          {
            required: true,
            message: "项目主要负责人现从事专业不能为空",
          },
        ],
        'projectLeader.task': [
          {
            required: true,
            message: "项目主要负责人在本项目中承担的任务不能为空",
          },
        ],
        'projectLeader.duty': [
          {
            required: true,
            message: "项目主要负责人职务不能为空",
          },
        ],
        'projectLeader.profTit': [
          {
            required: true,
            message: "项目主要负责人职称不能为空",
          },
        ],
        'projectLeader.profTitId': [
          {
            required: true,
            message: "项目主要负责人技术职称不能为空",
          },
        ],

      },
      oldPorjectList: [],
    }
  },
  watch: {
    activeForm: {
      immediate: true,
      handler (val) {
        // this.$refs.form?.clearValidate();
        this.oldUser = null;
        // document.getElementsByClassName("t-layout__content").scrollTop;
        const targetEle = document.getElementsByClassName("base-container")[0]
        if (targetEle) {
          const { pos, top } = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({ behavior: 'smooth', block: 'start', inline: "nearest" });
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
        // document.getElementById("main").scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"})
      }
    }
  },
  async created () {
    this.formData.isOldProject = this.$route.query.isOldProject || '0';
    this.formData.projectStatus = this.$route.query.projectStatus || '0';
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("任务id丢失返回项目");
      this.$router.push("/kjxm/pm/three-project-my");
      return false;
    }
    await Promise.all([this.getDataTypes(), this.getDeptTreeSelect(this.$store.state.user.deptId), this.getProfTitTreeSelect()]);
    this.taskId = taskId;

    this.getData()

    const activeForm = Number(sessionStorage.getItem(`${taskId}-activeForm`)) || 0;
    if (sessionStorage.getItem(`${this.taskId}-projectId`)) {
      this.$api.kjxm.threeProject.get(sessionStorage.getItem(`${this.taskId}-projectId`)).then(response => {

        this.adviceFunding = response.data.adviceFunding;
        this.subsidyFunding = response.data.subsidyFunding;

      }).catch((e) => {
        this.applyLoading = false;
        this.$message.error(e.toString());
      });
    } else {
      this.getUserInfo()
      this.activeForm = activeForm;
      this.applyLoading = false;
    }
  },
  mounted () {

  },
  beforeDestroy () {
    this.applyLoading = false;
  },
  methods: {
    getUserInfo () {
      this.$api.system.user.getBaseInfo().then(response => {
        this.formData.declareDeptName = response.data.dept.deptName;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },

    onProjectNameChange (val) {
      if (val) {
        this.$api.kjxm.project.getSimilarProjectByName({ keyWord: val }).then(res => {
          this.oldPorjectList = res.data || [];

        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    createKeyWordOptions (value) {
      this.dict.type.kjxm_key_word.push({
        label: `${value}`,
        value,
      });
    },
    onKeyWordChange (val) {
      console.log(this.formData.keyWord);

      // const keyword = this.formData.keyWord.concat(this.formData.digestKeyWordList).join(";")
      // if (keyword) {
      //   this.$api.kjxm.project.getSimilarProjectByName({ keyWord: keyword }).then(response => {
      //     this.formData.projectEsModelList = response.data || [];
      //   }).catch((e) => {
      //     this.$message.error(e.toString());
      //   });
      // }
    },


    onLeaderNameChange (val, content) {
      const index = this.projectLeaderOptions.findIndex(val => content?.option?.id === val.id)
      this.projectLeaderOptions[index].label = this.projectLeaderOptions[index].name;
      this.$set(this.projectLeaderOptions, index, this.projectLeaderOptions[index])
      // Object.assign(this.formData.projectLeader, content.option)
      const oldId = this.formData.projectLeader.id;
      this.$set(this.formData, "projectLeader", this.projectLeaderOptions[index])
      this.formData.projectLeader.id = oldId;
    },
    onProfTitIdChange (val, content) {
      this.formData.projectLeader.profTit = content.node.data.level;
    },

    onIdCardChange (val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.projectLeader.birthDate = birthday.slice(0, 7);
        this.$api.kjxm.project.findProjectMember(val).then(response => {
          this.oldUser = response.data;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },

    getProfTitTreeSelect () {
      return this.$api.system.profTit.list().then(response => {
        // this.profTitOptions = response.data;
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect () {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },

    close () {
      this.applyLoading = false;
      setTimeout(() => {
        this.$tab.closeOpenPage({ path: this.$route.meta.activeMenu || "/kjxm/apply/project-my" });
      }, 1000)
    },
    getData () {
      // 根据不同的activeForm 复查数据
      if (sessionStorage.getItem(`${this.taskId}-projectId`)) {
        this.applyLoading = true;
        const projectId = Number(sessionStorage.getItem(`${this.taskId}-projectId`));
        this.$api.kjxm.threeProject.get(projectId).then(response => {
          response.data.projectLeader = response.data.projectLeader ? response.data.projectLeader : this.formData.projectLeader;
          Object.assign(this.formData, response.data);
          this.formData.keyWord = response.data.keyWord.split(",").filter(item => item !== '')

          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
        // 取附件
        getFiles(sessionStorage.getItem(`${this.taskId}-projectId`)).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          const fileLists = []
          this.projectFileData.forEach((val, index) => {
            if (this.formData.isOldProject === '1') {
              this.projectFileData[index].c2 = '否';
            }
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
            fileLists.push(...this.projectFileData[index].fileIds)
          })
          if (fileLists.length > 0) {
            sessionStorage.setItem(`${this.taskId}-fileId`, res.data.length)
          }
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      }
    },
    getProjectId () {
      return sessionStorage.getItem(`${this.taskId}-projectId`)
    },
    isSubmit (name) {
      return sessionStorage.getItem(`${this.taskId}-${name}`) ? '已提交' : '未提交';
    },

    getDataTypes () {
      return getDictList(["project_type", "subject_classification", "sys_user_sex", "prof_tit", "degree", "education", "duty", "platform_type", "expect_result_type"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    createProjectLeaderOptions (value) {
      this.projectLeaderOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    remoteProjectLeaderMethod (search) {
      this.leaderLoading = true;

      this.$api.system.member.searchList({ name: search }).then(response => {
        this.projectLeaderOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.leaderLoading = false;
      }).catch((e) => {
        this.leaderLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit ({ validateResult, firstError }, type) {
      if (validateResult === true) {
        // if (Number(this.formData.adviceFunding) < Number(this.formData.subsidyFunding)) {
        //   const label = this.site_tag === 'jtt' ? '申请厅补助经费' : '申请集团补助经费';
        //   this.$message.error(`建议经费总概算:${this.formData.adviceFunding}不能小于${label}:${this.formData.subsidyFunding}`);
        //   return false
        // }
        const age = getIdCardAge(this.formData.projectLeader.idCard)
        if (age < 18) {
          this.$message.error(`项目主要负责人 身份证号 需满18岁`);
          return false
        }
        const birthday = getIdCardBirthday(this.formData.projectLeader.idCard)
        if (birthday.slice(0, 7) !== this.formData.projectLeader.birthDate) {
          this.$message.error(`项目主要负责人身份证号与出生年月 不一致`);
          return false
        }
        this.applyLoading = true;
        this.formData.keyWord = this.formData.keyWord.join(",")
        if (!sessionStorage.getItem(`${this.taskId}-projectId`)) {
          this.$api.kjxm.threeProject.add({
            ...this.formData,
          }).then(response => {
            sessionStorage.setItem(`${this.taskId}-projectId`, response.data.id)
            this.$message.success('提交成功');

            this.adviceFunding = this.formData.adviceFunding;
            this.subsidyFunding = this.formData.subsidyFunding;

            this.onSubmit8(type)
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.$api.kjxm.threeProject.edit({
            ...this.formData,
            // keyWord: this.formData.keyWord.join(","),
            id: Number(sessionStorage.getItem(`${this.taskId}-projectId`)),
            // projectStatus: this.formData.isOldProject === '1' ? null : '1',
          }).then(response => {
            // this.activeForm = 1;

            this.adviceFunding = this.formData.adviceFunding;
            this.subsidyFunding = this.formData.subsidyFunding;

            this.onSubmit8(type)
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        }
      } else {
        this.$message.error(firstError);
      }
    },
    onSubmit8 (type) {
      if (type === 1) {
        this.applyLoading = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val => {
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.kjxm.threeProject.edit({
          id: Number(sessionStorage.getItem(`${this.taskId}-projectId`)),
          sysAttMainVo: {
            sysAttMainIds,
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('提交成功');
          this.applyLoading = false;
          this.$router.push("/kjxm/pm/three-project-my");
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      } else {
        if (this.formData.isOldProject === '1') {
        } else {
          const isValidate = this.projectFileData.every(val => {
            if (val.require && val.fileIds.length <= 0) {
              this.$message.error(`需要上传${val.c1}`);
              return false;
            }
            return true
          })
          if (!isValidate) {
            return false
          }
        }
        if (!sessionStorage.getItem(`${this.taskId}-projectId`)) {
          this.$message.error("基本信息还未提交")
          this.applyLoading = false;
          return false;
        }
        this.applyLoading = true;
        this.isCommit = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val => {
          sysAttMainIds.push(...val.fileIds)
        })
        if (this.formData.isOldProject === '1') {
          this.$api.kjxm.threeProject.projectOldSubmit({
            id: Number(sessionStorage.getItem(`${this.taskId}-projectId`)),
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(val => {
            sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
            this.$message.success('提交成功');
            this.applyLoading = false;
            this.isCommit = false;
            this.close();
          }).catch((e) => {
            this.applyLoading = false;
            this.isCommit = false;
            this.$message.error(e.toString());
          });
        } else {
          this.$api.kjxm.threeProject.projectSubmit({
            // projectStatus: this.formData.isOldProject === '1' ? null : '2',
            id: Number(sessionStorage.getItem(`${this.taskId}-projectId`)),
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(val => {
            sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
            this.$message.success('提交成功');
            this.applyLoading = false;
            this.isCommit = false;
            this.close();
          }).catch((e) => {
            this.applyLoading = false;
            this.isCommit = false;
            this.$message.error(e.toString());
          });
        }
      }
    },
    activated () {
      // const newid = Number(new Date().getTime()) + Number(Math.random() * 10)

    },



  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}

/* popup的样式 */
.ol-popup {
  position: absolute;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 4px;
  transform: translate(10px, 25px);
  min-width: 200px;
  text-align: left;
  background-color: rgba(255, 255, 255, 0.8);
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-width: 10px;
  left: 50%;
  margin-left: -10px;
}

.ol-popup:before {
  border-width: 11px;
  left: 50%;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: "x";
}

.ol-popup-content {
  font-size: 14px;
}

.ol-popup-content-tab td:nth-child(2n+1) {
  font-weight: bold;
}

.ol-popup-content-tab td:nth-child(2n) {}

.require {
  color: red;
  margin-right: 3px;
}
</style>
